//
//  WCBDataSourceGenerator.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/21.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBDataSourceGenerator.h"
#import "TFWeakTimer.h"

static NSInteger kInterval = 10;

@interface WCBDataSourceGenerator()
@property (strong, nonatomic) NSArray *dataItems;
@property (strong, nonatomic) TFWeakTimer *timer;
@property (assign, nonatomic) NSInteger index;
@end

@implementation WCBDataSourceGenerator

+ (instancetype)sharedInstance
{
    static WCBDataSourceGenerator *g = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g = [[WCBDataSourceGenerator alloc] init];
    });
    return g;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"dateItem.plist" ofType:nil];
        NSArray *dicts = [NSArray arrayWithContentsOfFile:path];
        self.dataItems = [WCDataItem modelWithArray:dicts];
    }
    return self;
}

#pragma mark - Public
- (void)begin
{
    if (self.timer == nil) {
        self.timer = [TFWeakTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(generate) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
    }
}

- (void)end
{
    [self.timer invalidate];
    self.timer = nil;
    self.index = 0;
    if (self.delegate && [self.delegate respondsToSelector:@selector(generateCompletion)]) {
        [self.delegate generateCompletion];
    }
}

#pragma mark - Actions
- (void)generate
{
    NSInteger endIndex = self.index + kInterval;
    NSInteger length = 0;
    if (endIndex > self.dataItems.count) {
        length = self.dataItems.count - self.index;
        [self end];
    }
    else {
        length = kInterval;
    }
    
    NSArray *items = [self.dataItems subarrayWithRange:NSMakeRange(self.index, length)];
    if (self.delegate && [self.delegate respondsToSelector:@selector(generateDataWithItems:)]) {
        [self.delegate generateDataWithItems:items];
    }
    NSLog(@"%zd", self.index);
    self.index += length;
}
@end
